<template>
  <!--      
        title="提示"   title属性用于定义标题，它是可选的，默认值为空
        :visible.sync="dialogVisible"  visible属性，它接收Boolean，当为true时显示 Dialog
         width="30%"
        :before-close="handleClose"
     -->
  <el-dialog :title="title" v-model="dialogVisible" width="30%" :before-close="close">
    <p class="title">请输入类目名称：</p>
    <el-input v-model="name" placeholder="请输入内容"></el-input>
    <div class="dialog-footer">
      <span slot="footer">
        <el-button @click="close">取 消</el-button>
        <el-button type="primary" @click="submit">确 定</el-button>
      </span>
    </div>
  </el-dialog>
</template>

<script setup>
import { ref, watch } from "vue";
import api from '@/api/index'
import { ElMessage } from 'element-plus'
const props = defineProps(['input', 'cid'])
const emit = defineEmits(['updateViews'])
const dialogVisible = ref(false)
const title = ref('')
const name = ref('')
const id = ref('')

watch(() => props.input, (val) => {
  console.log('监听器=================val', val);
  name.value = val.name;
  id.value = val.id;
})

//确定按钮--------------
const submit = () => {
  if (title.value === '修改分类名称') {//修改操作
    updateCategory(name.value, id.value)
  } else if (title.value === '新增一级分类名称') {
    insertCategory(name.value)
  } else {
    //新增---子类目录---------- 
    insertItemCategory(name.value, props.cid)
  }
  // console.log('新增---子类目录---------- ',this.name,this.cid);
  //2. 隐藏弹框
  dialogVisible.value = false;
  //清空输入框
  name.value = '';
  //3. 更新视图
  emit('updateViews')
}
//新增子类接口---------- insertItemCategory --
const insertItemCategory = async (name, cid) => {
  let res = await api.insertItemCategory({ name, cid })
  console.log('新增子类接口---------', res.data.status);
  if (res.data.status == 200) {
    console.log(1)
    ElMessage({
      message: '恭喜你，新增成功',
      type: 'success'
    })
  } else {
    ElMessage.error('错了哦，新增失败');
  }
}
//修改接口---updateCategory----
const updateCategory = async (name, id) => {
  let res = await api.updateCategory({ name, id })
  console.log('修改接口1--------', res.data);
  if (res.data.status == 200) {
    ElMessage({
      message: `恭喜你，${res.data.msg}`,
      type: 'success'
    });
  } else {
    ElMessage.error('错了哦，修改失败');
  }
}
//一级分类名称新增---------- insertCategory---
const insertCategory = async (name) => {
  let res = await api.insertCategory({ name })
  console.log('一级分类名称新增-----', res.data);
  if (res.data.status == 200) {
    ElMessage({
      message: '恭喜你，新增成功',
      type: 'success'
    });
  } else {
    ElMessage.error('错了哦，新增失败');
  }
}
//取消
const close = () => {
  dialogVisible.value = false;
  name.value = ''
}
//暴露出
defineExpose({
  dialogVisible,
  title
})
</script>

<style lang="less" scoped>
.title {
  margin-bottom: 10px;
  font-weight: bold;
}

.dialog-footer {
  margin-top: 10px;
  text-align: center
}
</style>